package cn.fl.insurance.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.fl.preloan.dto.insurance.DeleteInsPlcStlDtlsRequest;
import cn.fl.preloan.dto.insurance.GetInsPlcStlDtlListRequest;
import cn.fl.preloan.dto.insurance.InsPlcStlDtlDTO;
import cn.fl.preloan.dto.insurance.ModifyInsPlcStlDtlRequest;
import cn.fl.commons.result.ResponseData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.insurance.condition.InsPlcStlDtlQueryCondition;
import cn.fl.insurance.service.IInsPlcStlDtlService;
import cn.fl.insurance.vo.InsPlcStlDtlVO;
import cn.fl.system.constant.SysLogConstant;

/**
 * @Description: 保险公司保单结算明细 控制层
 */
@Controller
@RequestMapping("/insurance/insPlcStlDtl")
public class InsPlcStlDtlController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(InsPlcStlDtlController.class);

    /**
     * InsPlcStlDtl 服务层BEAN
     */
    @Autowired
    private IInsPlcStlDtlService insPlcStlDtlService;

    /**
     * 贷前服务
     */
    @Autowired
    private cn.fl.preloan.IInsPlcStlDtlService iInsPlcStlDtlService;

    /**
     * 数据字典 服务层BEAN
     */
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;

    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toListPage.do", method = {RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toListPage", "加载InsPlcStlDtl列表页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("insurance/insPlcStlDtl/insPlcStlDtlList");
        return mav;
    }

    /**
     * 到新增页面
     */
    @RequestMapping(value = "/toAddPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toAddPage", "加载InsPlcStlDtl Add页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("insurance/insPlcStlDtl/insPlcStlDtlModify");
        //TODO 加载数据字典数据、传值等 ？

        return mav;
    }

    /**
     * 到修改页面
     */
    @RequestMapping(value = "/toModifyPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toModifyPage", "加载InsPlcStlDtl Modify页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("insurance/insPlcStlDtl/insPlcStlDtlModify");
        //TODO 加载数据字典数据、传值等 ？

        String id = request.getParameter("id");
        InsPlcStlDtlVO insPlcStlDtlVO = this.insPlcStlDtlService.selectById(Long.valueOf(id));
        mav.addObject("insPlcStlDtlVO", insPlcStlDtlVO);
        return mav;
    }

    /**
     * 初始化列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initInsPlcStlDtlList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        InsPlcStlDtlQueryCondition qc = new InsPlcStlDtlQueryCondition();
        //设置查询条件？
        String stlId = request.getParameter("stlId");
        if (StringUtils.isNotEmpty(stlId)) {
        	qc.setStlId(Long.valueOf(stlId));
        }else{
        	return null;
        }
        page.setCondition(qc);

        BaseLogUtils.info(logger, "initInsPlcStlDtlList", "初始化InsPlcStlDtl列表页面数据.DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
        Pager pager = this.insPlcStlDtlService.searchListPage(page);
        List<InsPlcStlDtlVO> list = (List<InsPlcStlDtlVO>) pager.getResultList();
        ListPageVO<InsPlcStlDtlVO> listPage = new ListPageVO<InsPlcStlDtlVO>(list, pager.getTotalCount());
        return listPage;
    }

    /**
     * 初始化列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initDtlList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initDtlList(HttpServletRequest request, HttpServletResponse response) {
        //InsPlcStlDtlQueryCondition qc = new InsPlcStlDtlQueryCondition();
        cn.fl.preloan.condition.InsPlcStlDtlQueryCondition qc = new cn.fl.preloan.condition.InsPlcStlDtlQueryCondition();
        //设置查询条件？
        String stlId = request.getParameter("stlId");
        if (StringUtils.isNotEmpty(stlId)) {
            qc.setStlId(Long.valueOf(stlId));
        }else{
            return null;
        }
        GetInsPlcStlDtlListRequest getRequest = new GetInsPlcStlDtlListRequest();
        getRequest.setCondition(qc);
        ResponseData responseData = iInsPlcStlDtlService.searchList(getRequest);
        BaseLogUtils.info(logger, "initInsPlcStlDtlList", "初始化InsPlcStlDtl列表页面数据.request:" + JSONObject.toJSONString(getRequest)
                + ",response: " + JSONObject.toJSONString(responseData), CurrentThreadContext.getCurrentUserName());
        List<InsPlcStlDtlVO> insPlcStlDtlVOS = new ArrayList<>();
        List<InsPlcStlDtlDTO> list = new ArrayList<>();
        InsPlcStlDtlVO insPlcStlDtlVO = null;
        if (responseData != null && responseData.getData() != null) {
            list = (List<InsPlcStlDtlDTO>) responseData.getData();
            for (InsPlcStlDtlDTO insPlcStlDtlDTO : list) {
                insPlcStlDtlVO = new InsPlcStlDtlVO();
                BeanUtils.copyProperties(insPlcStlDtlDTO,insPlcStlDtlVO);
                insPlcStlDtlVOS.add(insPlcStlDtlVO);
            }
        }
        //List<InsPlcStlDtlVO> list = this.insPlcStlDtlService.searchList(qc);
        if(CollectionUtils.isNotEmpty(insPlcStlDtlVOS)){
            ListPageVO<InsPlcStlDtlVO> listPage = new ListPageVO<InsPlcStlDtlVO>(insPlcStlDtlVOS,list.size());
            return listPage;
        }
        return null;
    }

    /**
     * 得到一条记录
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getById.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object getInsPlcStlDtlById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "getInsPlcStlDtlById", "获取InsPlcStlDtl数据,主键参数为空.", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        try {
            InsPlcStlDtlVO vo = this.insPlcStlDtlService.selectById(Long.valueOf(id));
            if (null == vo) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
                BaseLogUtils.info(logger, "getInsPlcStlDtlById", "获取InsPlcStlDtl数据不存在,ID:" + id, CurrentThreadContext.getCurrentUserName());
            }
            result.setData(vo);
            BaseLogUtils.info(logger, "getInsPlcStlDtlById", "获取InsPlcStlDtl数据成功,ID:" + id, CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.info(logger, "getInsPlcStlDtlById", "获取InsPlcStlDtl数据失败,ID:" + id + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "getInsPlcStlDtlById", "获取InsPlcStlDtl数据失败,系统错误.ID:" + id + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object addInsPlcStlDtl(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        InsPlcStlDtlVO entity = null;//获取参数
        try {
            entity = this.getRequestParamForInsPlcStlDtl(request);//获取参数
            Long id = this.insPlcStlDtlService.add(entity);
            result.setData(id);
            BaseLogUtils.info(logger, "addInsPlcStlDtl", "新增InsPlcStlDtl数据成功,ID:" + id + ".DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.info(logger, "addInsPlcStlDtl", "新增InsPlcStlDtl数据失败.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "addInsPlcStlDtl", "新增InsPlcStlDtl数据失败,系统错误.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/modify.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object modifyInsPlcStlDtl(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
        InsPlcStlDtlVO entity = null;
        try {
            entity = this.getRequestParamForInsPlcStlDtl(request);
            if (entity.getId() == null) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
                BaseLogUtils.info(logger, "modifyInsPlcStlDtl", "修改InsPlcStlDtl信息,主键参数为空！.ID:" + entity.getId(), CurrentThreadContext.getCurrentUserName());
                return result;
            }

            boolean success = this.insPlcStlDtlService.modify(entity);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
                BaseLogUtils.info(logger, "modifyInsPlcStlDtl", "修改InsPlcStlDtl数据失败.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
                return result;
            }
            BaseLogUtils.info(logger, "modifyInsPlcStlDtl", "修改InsPlcStlDtl数据成功.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.info(logger, "modifyInsPlcStlDtl", "修改InsPlcStlDtl数据失败.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "modifyInsPlcStlDtl", "修改InsPlcStlDtl数据失败,系统错误.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 修改结算明细记录的实际结算金额
     */
    @RequestMapping(value = "/modifyStlAmt.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object modifyStlAmt(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
        List<InsPlcStlDtlVO> list = null;
        try {
            list= this.getRequestParamForInsPlcStlDtls(request);
            //引入贷前服务
            ModifyInsPlcStlDtlRequest modifyRequest = new ModifyInsPlcStlDtlRequest();
            List<InsPlcStlDtlDTO> insPlcStlDtlDTOS = new ArrayList<>(list.size());
            InsPlcStlDtlDTO insPlcStlDtlDTO = null;
            for (InsPlcStlDtlVO insPlcStlDtlVO : list) {
                insPlcStlDtlDTO = new InsPlcStlDtlDTO();
                BeanUtils.copyProperties(insPlcStlDtlVO,insPlcStlDtlDTO);
                insPlcStlDtlDTOS.add(insPlcStlDtlDTO);
            }
            modifyRequest.setList(insPlcStlDtlDTOS);
            ResponseData responseData = iInsPlcStlDtlService.modifyInsPlcStlDtl(modifyRequest);
            BaseLogUtils.info(logger, "modifyStlAmt", "修改结算明细记录的实际结算金额.request:" + JSONObject.toJSONString(modifyRequest)
                    + ",response: " + JSONObject.toJSONString(responseData), CurrentThreadContext.getCurrentUserName());
            if (responseData.getCode().equals(ResponseData.FAIL_CODE)) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
                BaseLogUtils.info(logger, "modifyStlAmt", "修改结算明细记录的实际结算金额失败.DATA:" +list.size(), CurrentThreadContext.getCurrentUserName());
                return result;
            }
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.info(logger, "modifyStlAmt", "修改结算明细记录的实际结算金额失败.DATA:" + list.size() + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "modifyStlAmt", "修改结算明细记录的实际结算金额失败,系统错误.DATA:" + list.size() + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 删除数据
     */
    @RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO removeInsPlcStlDtlByIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String ids = request.getParameter("dtls");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
        if (StringUtils.isEmpty(ids)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "removeInsPlcStlDtlByIds", "删除InsPlcStlDtl数据,主键参数为空!", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        List<InsPlcStlDtlVO> list = this.getRequestParamForInsPlcStlDtls(request);;
        try {
            //引入贷前服务
            DeleteInsPlcStlDtlsRequest deleteRequest = new DeleteInsPlcStlDtlsRequest();
            List<InsPlcStlDtlDTO> insPlcStlDtlDTOS = new ArrayList<>(list.size());
            InsPlcStlDtlDTO insPlcStlDtlDTO = null;
            for (InsPlcStlDtlVO insPlcStlDtlVO : list) {
                insPlcStlDtlDTO = new InsPlcStlDtlDTO();
                BeanUtils.copyProperties(insPlcStlDtlVO,insPlcStlDtlDTO);
                insPlcStlDtlDTOS.add(insPlcStlDtlDTO);
            }
            deleteRequest.setList(insPlcStlDtlDTOS);
            deleteRequest.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
            ResponseData responseData = iInsPlcStlDtlService.deleteInsPlcStlDtls(deleteRequest);
            BaseLogUtils.info(logger, "removeInsPlcStlDtlByIds", "删除InsPlcStlDtl数据.request:" + JSONObject.toJSONString(deleteRequest)
                    + ",response: " + JSONObject.toJSONString(responseData), CurrentThreadContext.getCurrentUserName());
            //boolean success = this.insPlcStlDtlService.removeByIds(list);
            if (responseData.getCode().equals(ResponseData.FAIL_CODE)) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
                BaseLogUtils.info(logger, "removeInsPlcStlDtlByIds", "删除InsPlcStlDtl数据失败,", CurrentThreadContext.getCurrentUserName());
            }
            //BaseLogUtils.info(logger, "removeInsPlcStlDtlByIds", "删除InsPlcStlDtl数据成功," , CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.info(logger, "removeInsPlcStlDtlByIds", "删除InsPlcStlDtl数据失败,.ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "removeInsPlcStlDtlByIds", "删除InsPlcStlDtl数据失败,系统错误.ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 获取请求参数
     *
     * @param request 请求
     * @return
     */
    private List<InsPlcStlDtlVO> getRequestParamForInsPlcStlDtls(HttpServletRequest request) throws BaseException {
        String dtls = request.getParameter("dtls");//主键
        if (StringUtils.isBlank(dtls)) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "未找到修改的结算明细记录.");
        }

        List<InsPlcStlDtlVO> list= JSON.parseArray(dtls,InsPlcStlDtlVO.class);
        if(CollectionUtils.isNotEmpty(list)){
            Date now = new Date();
            for(InsPlcStlDtlVO vo:list){
                vo.setMdfTm(now);
                vo.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
            }
        }else{
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "未找到修改的结算明细记录.");
        }
        return list;
    }

    /**
     * 获取请求参数
     *
     * @param request 请求
     * @return
     */
    private InsPlcStlDtlVO getRequestParamForInsPlcStlDtl(HttpServletRequest request) throws BaseException {
        //TODO 获取参数
        String id = request.getParameter("id");//主键
        String plcStlId = request.getParameter("plcStlId");
        String stlBatNo = request.getParameter("stlBatNo");
        String insPlcId = request.getParameter("insPlcId");
        String insNo = request.getParameter("insNo");
        String buyWayCd = request.getParameter("buyWayCd");
        String insBgTm = request.getParameter("insBgTm");
        String insEndTm = request.getParameter("insEndTm");
        String insAmt = request.getParameter("insAmt");
        String insFee = request.getParameter("insFee");
        String rebateAmt = request.getParameter("rebateAmt");

        //TODO 验证参数并赋值
        InsPlcStlDtlVO entity = new InsPlcStlDtlVO();
        if (StringUtils.isNotBlank(id)) {
            entity.setId(Long.valueOf(id));
        }

//		if (StringUtils.isBlank(name)) {
//            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "名称不能为空.");
//      }
//      if (StringUtils.isNotBlank(num)) {
//          if (!StringUtils.isUnsignedNumeric(num)) {
//                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请填写正确的数字.");
//          }
//      }
//      entity.setX();

        Date tm = new Date();
        entity.setCrtTm(tm);
        entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
        entity.setMdfTm(tm);
        entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
        return entity;
    }
}

